package comp9417;

/**
 * Created by huy on 28/05/14.
 */
public final class ContinuousType implements AttributeType {
    @Override
    public double difference(Object v1, Object v2, Attribute attribute) {
        if (Double.isNaN((Double) v1) || Double.isNaN((Double) v2)) {
            return 1;
        }
        return normalize((Double) v1, attribute) - normalize((Double) v2, attribute);
    }

    @Override
    public Double predict(Classifier classifier, DataPoint point, int k) {
        return classifier.predictNumber(point, k);
    }

    @Override
    public Double predictWeighted(Classifier classifier, DataPoint point, int k) {
        return classifier.predictNumberWeighted(point, k);
    }

    @Override
    public void prune(Attribute attribute) {
        attribute.prune = (attribute.min == attribute.max);
    }

    @Override
    public Double prunedValue(Attribute regressionAttribute) {
        return regressionAttribute.max;
    }

    @Override
    public void addValueToDatapoint(Attribute attribute, DataPoint dataPoint, int index, String[] points) {
        double value;
        try {
            value = Double.parseDouble(points[index]);
            attribute.updateMinMax(value);
        } catch (NumberFormatException ex) {
            value = Double.NaN;
        }
        dataPoint.addValue(index, value);
    }

    // normalize the value between 0.0 and 1.0
    private double normalize(double value, Attribute attribute) {
        if (attribute.max == attribute.min) return 0.0;
        return (value - attribute.min) / (attribute.max - attribute.min);
    }
}
